package net.wicp.tams.common.connector.executor.busi;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.constant.StrPattern;

@Slf4j
public abstract class ClassPathXml {
	private final static Map<String, InputStream> parseXmlMap = new HashMap<String, InputStream>();
	static {
		List<URL> roots = IOUtil.findHasPackRootPath("connector");
		final Map<String, InputStream> tempMap = new HashMap<String, InputStream>();
		for (URL root : roots) {
			if ("jar".equals(root.getProtocol())) {
				try {
					Map<String, InputStream> is = IOUtil.getFilesFromJar(root.getPath(), "connector/", "xml");
					String fileDir = IOUtil.getCurFolder(ClassPathXml.class, false).getPath();
					File dir = new File(IOUtil.mergeFolderAndFilePath(fileDir, "/temp"));
					if (!dir.exists()) {
						dir.mkdir();
					}
					for (String key : is.keySet()) {
						if (StrPattern.checkStrFormat(Conf.get("common.connector.includejar.name.pattern"), key)
								&& key.contains(".jar")) {
							// log.info("commjar:{}",key);
							String[] paths = key.split("/");
							File newFile = new File(dir, paths[paths.length - 1]);
							log.info("newfile:{}", newFile.getPath());
							if (!newFile.exists()) {
								FileUtils.copyInputStreamToFile(is.get(key), newFile);
							}
							String filepathTrue = newFile.getPath().startsWith("file:") ? "jar:" + newFile.getPath()
									: "jar:file:" + newFile.getPath();
							// log.info("------------proppath:{}----------",filepathTrue);
							Map<String, InputStream> map2 = IOUtil.getFilesFromJar(filepathTrue, "connector/", "xml");
							tempMap.putAll(map2);
						} else {
							tempMap.put(key, is.get(key));
						}

					}
				} catch (Exception e) {
					log.error("加载properties错误", e);
				}
			}
		}
		for (String key : tempMap.keySet()) {
			String keytrue = key.replace(".xml", "").replaceFirst("connector/", "").replaceAll("/", ".").toLowerCase();
			parseXmlMap.put(keytrue, tempMap.get(key));
		}
	}

	public static InputStream getXmlStream(String appKey) {
		return parseXmlMap.get(appKey);
	}

}
